package com.rover.system.service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.grid.DataGrid;
import com.rover.system.entity.Code;
import com.rover.system.entity.CodeValue;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.grid.Page;
import com.rover.system.dao.BaseDao;


@Service
@Transactional
public class CodeValueService {
	protected Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private BaseDao dao;

    @Autowired
    private CodeService codeService;
	@Transactional(readOnly = true)
	public DataGrid query(Page page) throws Exception {
        DataGrid dataGrid=new DataGrid();

	    page.setFieldList(" new CodeValue(cv.id,cv.itemText,cv.itemValue,cv.description,cv.sequence,cv.treeCode) ");
        page.setTableName(" CodeValue cv left join cv.code ");
        String spareProperty = page.getParameter("spareProperty");
        String codeId = page.getParameter("codeId");
        //判断是否是根据  spareProperty来获取对应的编码值
        if(StringUtils.isNotBlank(spareProperty)){
            codeId=  codeService.getEntitySpareProperty(spareProperty).getId().toString();
        }
        String hql = "  1=1 ";
        Map<String, Object> params = new HashMap<String, Object>();
        if (StringUtils.isNotBlank( codeId)) {
            hql += " and cv.code.id=" + codeId ;
        }

        String treeCode = page.getParameter("treeCode");
        if(treeCode!=null)
        {
        if(StringUtils.isNotBlank(treeCode)){
            hql += " and treeCode like:treeCode and treeCode<>:treeCode2";
            params.put("treeCode", treeCode + "%");
            params.put("treeCode2", treeCode );
        }     else
            hql += " and length(treeCode)=3 ";
        }
          page.setWhere(hql);
        page.setWhereParams(params);

        dataGrid.setTotalCount(dao.countHql(page.getHQLTotalCount(),page.getWhereParams()));
		List<CodeValue> li=dao.findPageHql(page.getHQL(),page.getWhereParams(), page.getPageNo(),
				page.getPageSize());

        dataGrid.setResult(li);
		return dataGrid;
	}
	

	@Transactional
	public void save(CodeValue codeValue,String codeId) {
		if(codeValue.getCode()==null){
			codeValue.setCode(dao.<Code>get(Code.class,Integer.valueOf(codeId)));
		}

        dao.saveOrUpdate(codeValue);
	}
	/*
	 * 编码树添加
	 * */
	@Transactional
	public void treeSave(CodeValue codeValue,Integer codeId) {
			codeValue.setCode(dao.<Code>get(Code.class,codeId));
			codeValue.setTreeCode(getNextCode(codeValue.getpTreeCode()));
			CodeValue pCodeValue=null;
			 Map<String, Object> params = new HashMap<String, Object>();
			 params.put("treeCode", codeValue.getpTreeCode());
			 params.put("codeId", codeId);
			List<CodeValue> li=dao.findHql("from CodeValue cv where cv.treeCode=:treeCode and cv.code.id=:codeId",params);
			if(li.size()>0){
				pCodeValue=li.get(0);
			}
			codeValue.setpCodeValue(pCodeValue);
		  dao.save(codeValue);
	}
	@Transactional
	public void treeUpdate(CodeValue codeValue,Integer codeId) throws Exception {
		
		CodeValue oldCodeValue=dao.get(CodeValue.class, codeValue.getId());
		oldCodeValue.setDescription(codeValue.getDescription());
		oldCodeValue.setItemText(codeValue.getItemText());
		oldCodeValue.setItemValue(codeValue.getItemValue());
		oldCodeValue.setSequence(codeValue.getSequence());
		String oldCode=oldCodeValue.getTreeCode();
	    String	oldPCode=oldCodeValue.getTreeCode();
		if(oldPCode == null || oldPCode.equals("")){
			oldPCode="";
		}
		else
		{
			oldPCode=oldPCode.substring(0,oldPCode.length()-3);
		}
		if(!oldPCode.equals(codeValue.getpTreeCode())){
			
		    String strNewTreeCode=getNextCode(codeValue.getpTreeCode());
		    if(strNewTreeCode.startsWith(oldCode))
		    	throw new Exception("保存失败，原因是父节点不能变成它的子节点的节点！");
		    CodeValue pCodeValue=null;
		    //判断父节点是否是顶级节点
		   if(!codeValue.getpTreeCode().equals("")){
			   Map<String, Object> pParams = new HashMap<String, Object>();
			   pParams.put("treeCode", codeValue.getpTreeCode());
			   pCodeValue=dao.<CodeValue>findHql("from CodeValue cv where cv.treeCode=:treeCode",pParams).get(0);
		   }oldCodeValue.setpCodeValue(pCodeValue);
		    oldCodeValue.setTreeCode(strNewTreeCode);
		    Map<String, Object> params = new HashMap<String, Object>();
		    params.put("id", codeValue.getId());
		    params.put("codeId", codeId);
			List<CodeValue> li=dao.findHql("from CodeValue cv where cv.treeCode like '"+oldCode+"%' and cv.id<>:id and cv.code.id=:codeId",params);
            for(CodeValue cv:li){
                dao.executeHql("update CodeValue cv set cv.treeCode='"+strNewTreeCode+cv.getTreeCode().substring(oldCode.length())+"' where cv.id="+cv.getId().toString(),null);
            }
		}
		
		
		dao.update( oldCodeValue);
	}
	@Transactional
	public void delete(Integer id) {
        dao.delete(CodeValue.class,id);
	}
	
	/*
	 * 根据codeID获取对应的值列表
	 * @codeID  code表里的id
	 * */
	@Transactional(readOnly = true)
	public List<CodeValue> getCodeValue(Integer codeID) {
	return	dao.findHql("select new CodeValue(cv.id,cv.itemText,cv.itemValue) from CodeValue cv join cv.code where cv.code.id="+codeID.toString(),null);
	}
	/*
	 * 根据code名称获取对应的值列表
	 * @codeName  code表里的name
	 * */
	@Transactional(readOnly = true)
	public List<CodeValue> getCodeValue(String codeName) {
		 Map<String, Object> params = new HashMap<String, Object>();
		    params.put("codeName", codeName);
	return	dao.findHql("select new CodeValue(cv.id,cv.itemText,cv.itemValue) from CodeValue cv join cv.code where cv.code.name=:codeName",params);
	}
	/*
     * 获取treeCode的数据源
     * */
	@Transactional(readOnly = true)
    public List<CodeValue> getTreeList(String codeName){
		  Map<String, Object> params = new HashMap<String, Object>();
		    params.put("codeName", codeName);
		return	dao.findHql("select cv from CodeValue cv join cv.code where codeValue.pCodeValue is null and cv.code.name=:codeName",params);
	}
    /*
     * 获取treeCode的数据源
     * */
	@Transactional(readOnly = true)
    public List<CodeValue> getTreeList(Integer codeID){
		
		return	dao.findHql("select cv from CodeValue cv join cv.code where cv.pCodeValue is null and cv.code.id="+codeID.toString(),null);
	}
	
	 /// <summary>
    /// 取得下一个部门的编号
    /// </summary>
    /// <param name="con"></param>
    /// <param name="ParentDeptCode"></param>
    /// <returns></returns>
    private String getNextCode(String parentTreeCode)
    {
        String SQL = "select max(substring(treeCode,(length(treeCode)-3+1),3)) from CodeValue where 1=1  ";

        if (parentTreeCode == "")
        {
            SQL += " and length(treeCode)=3 ";
        }
        else
        {
            SQL += " and length(treeCode)=" + (parentTreeCode.length() + 3) + " and substring(treeCode,1," + parentTreeCode.length()+ ")='" + parentTreeCode + "' ";
        }
        Object MaxID = dao.uniqueResultHql(SQL,null);
        
        if (MaxID == null)
        {
            if (parentTreeCode == "")
                return "001";
            else
                return parentTreeCode + "001";
        }
        else
        {
            if (parentTreeCode == "")
                return String.format("%03d", (Long.valueOf(MaxID.toString()) + 1l));
            else
                return parentTreeCode + String.format("%03d", (Long.valueOf(MaxID.toString()) + 1l));
        }

    }
	/*
	 * 添加的时候判断名称是否重复
	 * @name 要判断的名称
	 * */
	public Boolean isItemTextRepeat(CodeValue codeValue,Integer codeId){
		String hql="select count(id) from CodeValue cv where cv.itemText=:itemText and cv.code.id=:codeId";
		 Map<String, Object> params=new HashMap<String, Object>();
		 params.put("itemText", codeValue.getItemText());
		 params.put("codeId", codeId);
		 if(codeValue.getId()!=null){
			 hql+=" and id<>:id";
			 params.put("id", codeValue.getId());
		 }
		 
		if(dao.countHql(hql, params)>0){
			return true;
		}
		else
			return false;
	}
	/*
	 * 添加的时候判断名称是否重复
	 * @name 要判断的名称
	 * */
	public Boolean isItemValueRepeat(CodeValue codeValue,Integer codeId){
		String hql="select count(id) from CodeValue cv where cv.itemValue=:itemValue and cv.code.id=:codeId";
		 Map<String, Object> params=new HashMap<String, Object>();
		 params.put("itemValue", codeValue.getItemValue());
		 params.put("codeId", codeId);
		 if(codeValue.getId()!=null){
			 hql+=" and id<>:id";
			 params.put("id", codeValue.getId());
		 }
			if(dao.countHql(hql, params)>0l){
			return true;
		}
		else
			return false;
	}

}
